package org.example.chat.websocket.nettyhandler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.example.chat.websocket.entity.ChannelContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 收不到客户端心跳时的处理器
 * @author cheval
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NoHeartBeatHandler extends ChannelDuplexHandler {
    @Autowired
    private ChannelContext channelContext;
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            // 服务端主动断开与客户端的连接，防止客户端假死
            channelContext.destroy(ctx.channel());
            log.info("检测客户端{}无心跳，服务端主动断开其连接 ",ctx.channel().id().toString());
        }
    }
}
